<?php

namespace app\admin\service;

use app\admin\validate\PluginValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\AdminNode;
use support\spark\model\system\Plugins;
use support\spark\plugin\helpers\Create;
use support\spark\plugin\helpers\Install;
use support\spark\plugin\helpers\Remove;
use support\spark\plugin\helpers\Uninstall;
use support\utils\SparkTools;

class PluginService
{

    /**
     * 获取所有的插件
     * @param $param
     * @return array
     */
    public function getAppList($param)
    {
        $where = [];
        if (!empty($param['title'])) {
            $where[] = ['title', 'like', '%' . $param['title'] . '%'];
        }

        if (!empty($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        }

        $pluginsModel = new Plugins();
        $list = $pluginsModel->getPaginateList($where,['*'],['id'=>'desc'],[],$param['limit']);
        return dataReturn(0,'ok',$list);
    }

    /**
     * 创建插件
     * @param $param
     * @return array
     */
    public function createPlugin($param)
    {
        $validate = new PluginValidate();
        if (!$validate->check($param)) {
            throw new  ApiException($validate->getError());
        }
        $pluginsName = $param['name'];
        // 检测插件名称是否存在
        $pluginsModel = new Plugins();
        $has = $pluginsModel->getInfoByWhere(['name' => $pluginsName], 'id');
        if (!empty($has)) {
            throw new  ApiException('该插件名已经存在，请换一个！');
        }
        Create::execute($pluginsName,$param['title'],$param['description'],$param['author'], $param['home_page'],$param['version']);
        // 写入数据库
        $param['create_time'] = now();
        $param['status'] = 1; // 未安装 //需要编辑安装sql  菜单
        $pluginsModel->insertOne($param);
        return dataReturn(0, '创建成功');

    }

    /**
     * 卸载插件
     * @param $id
     * @return array
     */
    public function uninstallPlugin($id)
    {
        $pluginsModel = new Plugins();
        $pluginInfo = $pluginsModel->getInfoByWhere(['id' => $id]);
        if (empty($pluginInfo)) {
            throw new  ApiException('插件不存在');
        }
        // 卸载插件
        $pluginsModel->updateById([
            'status' => 1,
            'update_time' => now()
        ], $id);
        // 卸载菜单
         Uninstall::execute($pluginInfo['name']);
         return dataReturn(0, '卸载成功');

//        return (new AdminNode())->updateByWehere([
//            'status' => 2, // 禁用
//            'update_time' => now()
//        ], ['type' => $pluginInfo['name']]);

    }

    /**
     * 安装插件
     * @param $id
     * @return array
     */
    public function installPlugin($id)
    {
        $pluginsModel = new Plugins();
        $pluginInfo = $pluginsModel->getInfoByWhere(['id' => $id]);
        if (empty($pluginInfo)) {
            throw new  ApiException('插件不存在');
        }
        // 安装插件
        $pluginsModel->updateById([
            'status' => 2,
            'update_time' => now()
        ], $id);
        // 菜单未安装过，则执行安装脚本
        $nodeModel = new AdminNode();
        $hasMenu = $nodeModel->getInfoByWhere(['type' => $pluginInfo['name']]);
        if (empty($hasMenu)) {
            Install::execute($pluginInfo['name']);
        }
       $nodeModel->updateByWhere([
            'status' => 1, // 启用
            'update_time' => now()
        ], ['type' => $pluginInfo['name']]);
        return dataReturn(0, '安装成功');
    }

    /**
     * 删除插件
     * @param $id
     * @return array
     */
    public function deletePlugin($id)
    {
        $pluginsModel = new Plugins();
        $pluginInfo = $pluginsModel->findOne(['id' => $id])['data'];
        if (empty($pluginInfo)) {
            throw new  ApiException('插件不存在');
        }
        // 删除目录
        Remove::execute($pluginInfo['name']);
        // 删除安装项
        $pluginsModel->delById($id);
        return dataReturn(0, '删除成功');
    }

    /**
     * 插件打包
     * @param $name
     * @return array
     */
    public function doPack($name)
    {

        $dir = run_path() . '/plugin' . '/' . $name;
        if (!is_dir($dir)) {
            return dataReturn(-1, '插件不存在');
        }
        try {
            SparkTools::dirZip($name . '.zip', $dir, run_path().'/plugin/' );
        } catch (\Exception $e) {
            return dataReturn(-2, '插件打包错误:' . $e->getMessage());
        }

        return dataReturn(0, '打包成功');
    }



}
